/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.skycode.core.manager;

import com.skycode.core.common.UtilCore;
import com.skycode.core.configuracion.WebServletContextListener;
import com.skycode.core.mbean.ApplicationMBean;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import jxl.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

/**
 * @author SkyCode (skycode@gmail.com)
 * @since 07/02/2014
 * @version 1.0
 */
@Service
public class RecursosManager implements Serializable {

    private static Logger logger = Logger.getLogger(RecursosManager.class);

    public DataSource obtenerDataSource() throws NamingException {
        ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext().getBean("applicationMBean");
        InitialContext initctx = new InitialContext();
        DataSource ds = (DataSource) initctx.lookup(applicationMBean.getDataSourceName());

        return ds;
    }

    public Connection obtenerConexionDataBase() {

        Connection cnx = null;
        try {
            DataSource ds = obtenerDataSource();
            cnx = ds.getConnection();
        } catch (Exception e) {
            cnx = null;
            logger.error(e);
        }

        return cnx;
    }

    public String construirTitulo(final String keyEntidad, final int accion, final String... otros) {
        String retorno = null;
        StringBuilder sbTitulo = new StringBuilder();

        ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext().getBean("applicationMBean");

        if (accion == applicationMBean.getLista()) {
            sbTitulo.append(UtilCore.Internacionalizacion.getMensajeInternacional("general.titulo.lista"));
        } else if (accion == applicationMBean.getNuevo()) {
            sbTitulo.append(UtilCore.Internacionalizacion.getMensajeInternacional("general.titulo.nuevo"));
        } else if (accion == applicationMBean.getEditar()) {
            sbTitulo.append(UtilCore.Internacionalizacion.getMensajeInternacional("general.titulo.editar"));
        } else if (accion == applicationMBean.getVer()) {
            sbTitulo.append(UtilCore.Internacionalizacion.getMensajeInternacional("general.titulo.ver"));
        }
        sbTitulo.append(" ");
        sbTitulo.append(UtilCore.Internacionalizacion.getMensajeInternacional(keyEntidad));

        retorno = sbTitulo.toString();

        return retorno;
    }

    public String viewReportePdf(HashMap hmParametros, String reporte, String nombreArchivo) throws FileNotFoundException, JRException, IOException, SQLException {
        InputStream ie = null;
        Connection c = null;
        try {
            ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext().getBean("applicationMBean");
            File file = new File(applicationMBean.getRutaArchivos());
            ie = new FileInputStream(new File(file.getCanonicalPath(), "jaspers" + file.separator + reporte + ".jasper"));
            c = applicationMBean.obtenerConexionDataBase();
            System.out.println("CONEXION : " + c);
            if (c != null) {
                logger.info("P_DIRECTORIO_REPORTES: " + file.getCanonicalPath());
                hmParametros.put("P_DIRECTORIO_PRINCIPAL", file.getCanonicalPath() + file.separator);
                hmParametros.put("P_LOGO", "ERP.png");
                hmParametros.put(JRParameter.REPORT_LOCALE, new Locale("es_PE"));
                hmParametros.put(JRParameter.REPORT_TIME_ZONE, applicationMBean.getTimeZone());
                JasperPrint jasperPrint = JasperFillManager.fillReport(ie, hmParametros, c);
                logger.info("el jasperProcesado: " + jasperPrint.toString());
                byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
                FacesContext context = FacesContext.getCurrentInstance();
                HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
                response.addHeader("Content-disposition",
                        "attachment;filename=" + nombreArchivo);
                response.setContentLength(bytes.length);
                response.getOutputStream().write(bytes);
                response.setContentType("application/pdf");
                context.responseComplete();
            } else {
                logger.error("NO SE PUEDO EJECUTAR LA IMPRESION LA CONEXION ES NULA");
                System.out.println("NO SE PUEDO EJECUTAR LA IMPRESION LA CONEXION ES NULA");
            }

            return null;
        } catch (JRException ex) {
            logger.error("Error al rellenar el reporte " + ex.getMessage());
            logger.error(ex);
            showError(ex.getMessage());
        } catch (IOException ex) {
            logger.error("Error al leer el jasper " + ex.getMessage());
            logger.error(ex);
            showError(ex.getMessage());
        } catch (Throwable ex) {
            logger.error("Otros errores con el jasper " + ex.getMessage());
            logger.error(ex);
            showError(ex.getMessage());
        } finally {
            try {
                if (c != null) {
                    c.close();
                }
                if (ie != null) {
                    ie.close();
                }
            } catch (IOException ex) {
                logger.error(ex);
                showError(ex.getMessage());
            }
            return null;
        }
    }

    public void generarExcel(String cabecera, List listaExportar, String nombreArchivo) {
        try {
            ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext().getBean("applicationMBean");
            String ruta = applicationMBean.getRutaArchivos();
            File f = new File(ruta, nombreArchivo);
            f.createNewFile();
            WritableWorkbook workbook = Workbook.createWorkbook(f);

            WritableFont fuenteCelda = null;
            WritableCellFormat formatoCelda = null;
            WritableSheet sheet = workbook.createSheet("REPORTE", 0);

            // imprimiendo titulos
            fuenteCelda = new WritableFont(WritableFont.createFont("Calibri"), 8, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.WHITE);
            formatoCelda = new WritableCellFormat(fuenteCelda);
            formatoCelda.setBackground(Colour.RED);
            formatoCelda.setAlignment(Alignment.CENTRE);
            formatoCelda.setVerticalAlignment(VerticalAlignment.TOP);

            formatoCelda.setBorder(Border.ALL, BorderLineStyle.NONE);

            StringTokenizer cabecera_array = new StringTokenizer(cabecera, "|");
            int columnas = 0;
            while (cabecera_array.hasMoreTokens()) {
                Label label;
                label = new Label(columnas, 0, cabecera_array.nextToken(), formatoCelda);
                sheet.addCell(label);
                columnas++;
            }

            CellView cv = new CellView();
            // Anchos de columnas
            for (int j = 0; j < columnas; j++) {
                cv = sheet.getColumnView(j);
                cv.setAutosize(true);
                sheet.setColumnView(j, cv);
            }

            fuenteCelda = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            formatoCelda = new WritableCellFormat(fuenteCelda);
            formatoCelda.setBackground(Colour.WHITE);
            formatoCelda.setAlignment(Alignment.GENERAL);
            formatoCelda.setBorder(Border.ALL, BorderLineStyle.THIN);

            int fila = 1;
            for (Iterator iter = listaExportar.iterator(); iter.hasNext();) {
                String registro = (String) iter.next();
                StringTokenizer registro_array = new StringTokenizer(registro, "|");
                int columnas_registro = 0;
                while (registro_array.hasMoreTokens()) {
                    Label label;
                    label = new Label(columnas_registro, fila, registro_array.nextToken(), formatoCelda);
                    sheet.addCell(label);
                    columnas_registro++;
                }

                fila++;
            }
            workbook.write();
            workbook.close();
        } catch (Exception e) {
            logger.error(e);
        }
    }

    public void showMessage(String msjResumen) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_INFO, msjResumen, null);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showMessage(String msjResumen, String msjDetalle) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_INFO, msjResumen, msjDetalle);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showWarning(String msjResumen) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_WARN, msjResumen, null);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showWarning(String msjResumen, String msjDetalle) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_WARN, msjResumen, msjDetalle);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showError(String msjResumen) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, msjResumen, null);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showError(String msjResumen, String msjDetalle) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, msjResumen, msjDetalle);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showFatal(String msjResumen) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, msjResumen, null);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }

    public void showFatal(String msjResumen, String msjDetalle) {
        FacesMessage msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, msjResumen, msjDetalle);
        FacesContext.getCurrentInstance().addMessage(null, msj);
    }
}
